(async ()=>{
    function getParam(name){
        var r = window.location.href.split('?');
        if(!r[1]) return null;
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        r = r[1].match(reg);
        if (r != null) return decodeURIComponent(r[2]);
        return null;
    }

    let productId = getParam('productId')
    console.log(productId)
    let product = await (await fetch(`http://localhost:3001/product?productId=${ productId }`)).json()
    // console.log(product)

    let imgs = product.imgs.split(',')
    for(let i = 0; i < imgs.length; i ++){

    }

    // document.querySelector('#price').innerHTML = product.price
    document.querySelector('#name').innerHTML = product.name
    document.querySelector('#content').innerHTML = product.content.replace(/\.?\//g,'http://localhost:3001/')

    let max = 0,min = Infinity,skuDivs = []
    for(let i = 0; i < product.skus.length; i ++){
        let sku = product.skus[i],salePrice = sku.salePrice / 100
        if(salePrice > max) max = salePrice
        if(salePrice < min) min = salePrice

        let skuDiv = document.createElement('div')
        skuDiv.className = 'skuDiv'
        skuDiv.innerHTML = sku.props
        $('#skus').appendChild(skuDiv)
        skuDiv.addEventListener('click',event => {
            changeSkuIndex(i)
        })
        skuDivs.push(skuDiv)
    }

    let skuIndex = 0
    function changeSkuIndex(index){
        skuDivs[skuIndex].className = 'skuDiv'
        skuIndex = index
        skuDivs[skuIndex].className = 'skuDiv active'
        $('#skuName').innerHTML = product.skus[skuIndex].props
        $('#skuPrice').innerHTML = product.skus[skuIndex].salePrice
    }
    changeSkuIndex(0)

    function $(flog){
        return document.querySelector(flog)
    }

    $('#price').innerHTML = `${min}~${max}`
    
    $('#changeSku').addEventListener('click',event => {
        $('#sku').style.display = 'block'
    })

    $('#skuBoxCover').addEventListener('click',event => {
        $('#sku').style.display = 'none'
    })
    $('#goCar').addEventListener('click',event => {
        let = `skuId=${product.skus[skuIndex].skuId}`
        // location.href = `./car.html?skuId=${}`
        $('#sku').style.display = 'none'
    })

})()